/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.deneme.users.dao;

import com.deneme.users.model.User;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Repository
@Transactional
public class UserDAO {

    @Autowired
    private SessionFactory sessionFactory;

    @SuppressWarnings("unchecked")
    public User findByUserName(String username) {

        List<User> users = new ArrayList<User>();

        users = sessionFactory.getCurrentSession()
                .createQuery("from User where username=?")
                .setParameter(0, username)
                .list();

        if (users.size() > 0) {
            return users.get(0);
        } else {
            return null;
        }

    }

    public String kaydet(User user) {
        Session session = sessionFactory.getCurrentSession();
        session.save(user);
        return "/home.xhtml";
    }

    public List<User> allUsers() {
        Session session = sessionFactory.getCurrentSession();
        List users = session.createQuery("from User").list();

        return users;
    }

//    public User suYazar(String yazar) {
//        Session session = sessionFactory.getCurrentSession();
//        return em.find(User.class, yazar);
//    }

    public void delete(User user) {
        Session session = sessionFactory.getCurrentSession();
        session.delete(user);

    }

    public void update(User user) {
        Session session = sessionFactory.getCurrentSession();
        session.merge(user);
    }

}
